/*
* 路由
*
*/

import nProgress from "nprogress"; // 进度条
import 'nprogress/nprogress.css';
import { createRouter, createWebHistory } from 'vue-router';
import { routerArray } from './routers';
import { PAGE_PATH_LOGIN, PAGE_PATH_404 } from '@/constants/common-const';
import { localClear } from '@/utils/local-util';
import { sessionClear } from '@/utils/session-util';
import { HOME_PAGE_PATH } from '@/constants/system/home-const';
import { useUserStore } from '@/store/system/user';
import { ElMessage } from 'element-plus';

// 创建路由
export const router = createRouter({
    history: createWebHistory(),
    routes: routerArray,
    strict: true, // 适用所有路由
    scrollBehavior: () => ({ left: 0, top: 0 }), // 滚动行为
});

// ========================= 路由加载前 =========================
router.beforeEach(async (to, from, next) => {
    // 开启进度条
    nProgress.start(); 
    // 公共页面任何时候都可以跳转
    if(to.path == PAGE_PATH_LOGIN || 
        to.path == PAGE_PATH_404) {
        next();
        return;
    };
    // 验证登录
    const token = useUserStore().token;
    if (!token) {
        ElMessage({
            showClose: true,
            message: '您还没有登录，请先进行登录',
            type: 'error'
        });
        useUserStore().$reset();
        localClear();
        sessionClear();
        next({
            path:PAGE_PATH_LOGIN
        });
        return;
    };
    // 首页（需要登录，但不需要验证权限）
    if(to.path == HOME_PAGE_PATH) {
        next();
        return;
    };
    next();
});

// ========================= 路由加载后 =========================
router.afterEach(() => {
    nProgress.done();
});